<!--回收站-->
<template>
<a-card >
		<NoAuthPage v-showNoAuth="'D6-1'" :imgBoxStyle="{height:'40vh',margin:0}"/>
    <a-row v-userAuth="'D6-1'">
        <div style="margin:0 0 1em 0;">
        	<a-tooltip placement='bottom' v-userAuth="'D6-2'">
	            <template slot='title'>
	                <span>{{$t('Restore')}}</span>
	            </template>
            	<a-button :disabled="selectedRowKeys.length==0" type='primary' style="margin-right:1em;" @click="selected('recy')">
	            	<!-- <a-icon :component="regain" /> -->
								<!-- <a-icon type="retweet" /> -->
								<!-- <i class="icon icon-recycleout16f"></i> -->
								<Iconfont class="icon" type="icon-recycleout16f"></Iconfont>
								{{$t('Restore')}}
            	</a-button>
	        </a-tooltip>
        	<a-tooltip placement='bottom' v-userAuth="'D6-3'">
	            <template slot='title'>
	              <span>{{$t('Delete')}}</span>
	            </template>
            	<a-button :disabled="selectedRowKeys.length==0" type='danger' style="margin-right:1em;" @click="selected('delete')">
								<!-- icon='close-circle' -->
								<!-- <i class="icon icon-error16f"></i> -->
								<Iconfont class="icon" type="icon-error16f"></Iconfont>
								{{$t('Delete')}}
							</a-button>
	        </a-tooltip>
        </div>
        
        <a-table class='tabstyle' :columns="rcolumns" :loading="loading" :rowSelection='{type:"radio",selectedRowKeys:selectedRowKeys,onChange:onSelectChange,onSelect:onSelect}' 
				 :dataSource="rdata" size="small" :pagination='pagination' rowKey="id"
				 :locale="defaultSetting">
            <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" class='custom-filter-dropdown'>
                <a-input v-ant-ref="c => searchInput = c" :placeholder="$t('Enter')+$t('Search-content')" :value="selectedKeys[0]" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm)" style="width: 188px; margin-bottom: 8px; display: block;" />
                <a-button type='primary' @click="() => handleSearch(selectedKeys, confirm)" icon="search" size="small" style="width: 90px; margin-right: 8px">{{$t('Search')}}</a-button>
                <a-button @click="() => handleReset(clearFilters)" size="small" style="width: 90px">{{$t('Reset')}}</a-button>
            </div>
            <a-icon slot="filterIcon" slot-scope="filtered" type='search' :style="{ color: filtered ? '#108ee9' : undefined }" />
            <template slot="customRender" slot-scope="text">
                <span v-if='searchText'>
                    <template v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))">
                        <mark v-if="fragment.toLowerCase() === searchText.toLowerCase()" :key="i" class="highlight">{{fragment}}</mark>
                        <template v-else>{{fragment}}</template>
                    </template>
                </span>
                <template v-else>{{text}}</template>
            </template>
        </a-table>
        
				<!--块设备恢复-->
        <a-modal :title="$t('Block')+' '+$t('Restore')" v-model='recy' @cancel='cancelhandle' width='35%' @ok='restore' :cancelText="$t('Cancel')" :okText="$t('Sure')" :maskClosable='false' v-dragModal>
    		<a-spin size="large" style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%" tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
	        <a-form :form='form'>
	            <a-form-item :label="$t('Block-name')" v-bind='formlayout'>
	                <a-input v-decorator="['newblock',{
	                    rules:[{required:true,message:$t('Enter')+$t('Block-name')},
							{pattern:namePattern,message:$t('Not_enter_special_characters')}],initialValue:this.record.name
	                }]" :placeholder="$t('Enter')+$t('Block-name')">
	                </a-input>
	            </a-form-item>
	        </a-form>
	    </a-modal>
    </a-row>
</a-card>
</template>

<script>
	import {
	    setTimeout
	} from 'timers';
	// import regain from '../../../../static/images/svg/ic_regain_normal.svg'

	import EmptyData from '@/components/common/EmptyData'
	import NoAuthPage from '@/components/common/NoAuthPage'

	import request from '@/request/request'

	export default {
	    name: "Recycle",
    	props:['flag'],
	  	// template: '<a-icon :component="regain" />',
		components: { EmptyData, NoAuthPage },
	    data() {
	        return {
            	form:this.$form.createForm(this),
            	formlayout:{
	                labelCol:{span:6},
	                wrapperCol:{span:14}
	            },
	            rcolumns:[{
						title: "ID",
						dataIndex: "id",
						key: "id",
						ellipsis: true,
					},
					{
						title: this.$t('Block-name'),
						dataIndex: "name",
						key: "name",
						ellipsis: true,
						sorter: (a, b) => a.name.length - b.name.length,
						scopedSlots: {
							filterDropdown: 'filterDropdown',
							filterIcon: 'filterIcon',
							customRender: 'customRender',
						},
						onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
						onFilterDropdownVisibleChange: (visible) => {
							if (visible) {
								setTimeout(() => {
									this.searchInput.focus()
								}, 0)
							}
						}
					},
					{
						title: this.$t('Pool')+this.$t('Name'),
						dataIndex:'pool_name',
						key:'pool_name',
						ellipsis: true
					},
					{
						title: this.$t('Protect')+this.$t('Deadline'),
						dataIndex:'deferment_end_time',
						key:'deferment_end_time',
						ellipsis: true
					},
					{
						title: this.$t('Delete')+this.$t('Time'),
						dataIndex:'deletion_time',
						key:'deletion_time',
						ellipsis: true
					}
				],
	            searchText: '',
	            searchInput: null,
	            pagination:{
	                defaultPageSize:5,
	                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
	                showSizeChanger:true,
	                pageSizeOptions: ['5', '10', '15', '20'],
	                onShowSizeChange:(current, pageSize)=>this.pageSize = pageSize,
					buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
	            },
	            selectedRowKeys:[],
	            rdata: [],
	            target:'',
	            // regain,
            	recy:false,
            	record:[],
				loading:true,
				spinning:false,
				defaultSetting: {emptyText:<EmptyData />}
	        }
		},
		computed:{
			getlanguage(){
				return this.$store.state.language
			}
		},
		watch:{
        	flag(val){
				this.getdata()
			},
			getlanguage(val){
				this.rcolumns=[{
						title: "ID",
						dataIndex: "id",
						key: "id",
						ellipsis: true
					},
					{
						title: this.$t('Block-name'),
						dataIndex: "name",
						key: "name",
						ellipsis: true,
						sorter: (a, b) => a.name.length - b.name.length,
						scopedSlots: {
							filterDropdown: 'filterDropdown',
							filterIcon: 'filterIcon',
							customRender: 'customRender',
						},
						onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
						onFilterDropdownVisibleChange: (visible) => {
							if (visible) {
								setTimeout(() => {
									this.searchInput.focus()
								}, 0)
							}
						}
					},
					{
						title: this.$t('Pool')+this.$t('Name'),
						dataIndex:'pool_name',
						key:'pool_name',
						ellipsis: true
					},
					{
						title: this.$t('Protect')+this.$t('Deadline'),
						dataIndex:'deferment_end_time',
						key:'deferment_end_time',
						ellipsis: true
					},
					{
						title: this.$t('Delete')+this.$t('Time'),
						dataIndex:'deletion_time',
						key:'deletion_time',
						ellipsis: true
					}
				]
			}
		},
		created(){
			this.addListenerfun('block',this.getdata) //通知交互：监听变化 刷新
		},
	    mounted(){
	    	this.getdata()
	    },
	    methods: {
	    	getdata(){
				this.loading = true
	    		request('get', 'block/trash').then(res=>{
					// console.log('块设备回收站列表',res)
						if(res.data.flag == 1) {
							this.model(res.data.id) //返回模板
							this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
						}else {
							this.rdata = res.data;
							// this.loading = false;
						}
	    		}).catch(err => {
						// this.loading = false;
					}).finally(() => {
						this.loading = false;
					})
	    	},
	        handleSearch(selectedKeys, confirm) {
	            confirm()
	            this.searchText = selectedKeys[0]
	        },
	
	        handleReset(clearFilters) {
	            clearFilters()
	            this.searchText = ''
	        },
			onSelect(record,selected,selectedRows) {
				this.target = record.name;
				this.record = record;
			},
	        onSelectChange (selectedRowKeys, selectedRow) {
//	        	if(selectedRowKeys.length!=0){
//		        	this.target = this.rdata[selectedRowKeys].name
//	        	}
		        // for(var i=0;i<this.rdata.length;i++){
	        	// 	if(ids == this.rdata[i].id){
	        	// 		this.target = this.rdata[i].name
	        	// 		this.record = this.rdata[i]
	        	// 	}
	        	// }
		        this.selectedRowKeys = selectedRowKeys
	        },
	        selected(name){
	          if(this.selectedRowKeys.length!=0){
	              if(name == 'recy'){
	                  this.recy = true
	              }
	              else if(name == 'delete'){
	              	this.delete()
	              }
	          }
	          else
	            this.$notification['error']({
	            	message:this.$t('Choose')+this.$t('Operating-object')
	            })
	        },
			//块设备恢复
	    restore(e){
	      e.preventDefault();
	      this.form.validateFields((err,value)=>{
				if(!err){
					this.spinning = true
					request('post', 'block/trash/restore', {
						pool_id: this.record.pool_id,
						image_id: this.record.id,
						new_image_name: value.newblock, //要恢复的块设备名称
						old_block_name: this.record.name,
						pool_name: this.record.pool_name
					})
					// this.$axios({
					// 	method: 'post',// 以前是delete
					// 	url: this.allurl+'block/trash/restore',//以前是 block/trash/
					// 	data: {
					// 		pool_id: this.record.pool_id,
					// 		image_id: this.record.id,
					// 		new_image_name: value.newblock, //要恢复的块设备名称
					// 		old_block_name: this.record.name,
					// 		pool_name: this.record.pool_name
					// 		// pool:this.record.pool_name,
					// 		// id:this.record.id,
					// 		// new_name:value.newblock,
					// 	}
					// })
					.then(res=>{
						// console.log('回收站恢复操作', res)
						this.model(res.data.id) //返回模板
						this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
						// this.gettask()  //任务栏信息
						this.spinning = false
						this.recy = false
						this.$emit('omodal',false, false) 
						this.form.resetFields();
						this.getdata()
						this.selectedRowKeys = []
					}).catch(err => {
						this.spinning = false
						this.recy = false
						this.$emit('omodal',false, false) 
						this.form.resetFields();
					})	
				}
	        })
	    },
//	        restore(){
//	            this.$confirm({
//	                title:'设备恢复',
//	                content:'你确定恢复'+this.target+'吗？',
//	                okText:'确定',
//	                okType:'danger',
//	                cancelText:'取消',
//	                onOk(){
//	                    console.log('rollback')
//	                    this.$axios.post(this.allurl+'block/trash',{
//	                    	
//	                    }).then(res=>{
//	                    	console.log(res)
//	                    })
//	                },
//	                onCancel(){
//	
//	                }
//	            })
//	        },
				//删除块设备
	      delete(){
					const nowTimestring = (new Date()).valueOf();
					const endTimestring = (new Date(this.record.deferment_end_time)).valueOf();
					let contentTips = '';
					if(nowTimestring >= endTimestring) {// 已经过了保护截至时间
						contentTips = this.$t('Sure-to-del')+": "+this.target+' ？';
					}else {
						contentTips = this.$t('Sure-to-del2')+": "+this.target+' ？';
					}
	        let _this = this
	        this.$confirm({
	          title: this.$t('Delete-permanently'),
	          content: contentTips,
	          cancelText:this.$t('Cancel'),
						okText:this.$t('Sure'),
	          okType:'danger',
	          onOk(){
	            // _this.$axios({
							// 	method: 'delete',
							// 	url: _this.allurl+'block/trash/',
							// 	data: {
							// 		pool_id: _this.record.pool_id,
							// 		image_id: _this.record.id,
							// 		force: true,
							// 		name: _this.record.name,
							// 		pool_name:  _this.record.pool_name,

		          //     // pool:_this.record.pool_name,
		          //     // id:_this.record.id,
		          //     // name:_this.record.name,
		          //   }
	          	// })
							request('DELETE', 'block/trash/', {
								pool_id: _this.record.pool_id,
								image_id: _this.record.id,
								force: true,
								name: _this.record.name,
								pool_name:  _this.record.pool_name,
							})
							.then(res=>{
									_this.model(res.data.id) //返回模板
                  _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                	// _this.gettask() //任务栏通知
	                _this.getdata()
									_this.selectedRowKeys = [];
	            })
	          },
	          onCancel(){
	
	          }
	        })
	      },
	        cancelhandle(){
				// this.recy = false
				this.$emit('omodal',false ,true)
            	this.form.resetFields();
	        }
	    }
	};
</script>

